package com.contactsconverter.activity;

import java.io.File;
import java.io.FileOutputStream;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import com.contactsconverter.adapter.CTContactAdapter;
import com.contactsconverter.db.CTSIMDao;
import com.contactsconverter.model.CTContactModel;
import com.contactsconverter.model.CTNumberModel;
import com.contactsconverter.utils.CTUtils;
import com.contactsconverter.R;
import com.difsonapps.contacttranslator.dto.NumberDTO;
import com.difsonapps.contacttranslator.dto.NumberTypeEnum;

import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v7.widget.PopupMenu;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.NavUtils;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ContentProviderOperation;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.OperationApplicationException;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.RemoteException;
import android.provider.ContactsContract;
import android.support.v4.view.ViewPager;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class CTContactsActivity extends ActionBarActivity implements ActionBar.TabListener {

	/**
	 * The {@link android.support.v4.view.PagerAdapter} that will provide
	 * fragments for each of the sections. We use a {@link FragmentPagerAdapter}
	 * derivative, which will keep every loaded fragment in memory. If this
	 * becomes too memory intensive, it may be best to switch to a
	 * {@link android.support.v4.app.FragmentStatePagerAdapter}.
	 */
	SectionsPagerAdapter mSectionsPagerAdapter;
	private final String TAG = this.getClass().getSimpleName();
	/**
	 * The {@link ViewPager} that will host the section contents.
	 */
	ViewPager mViewPager;
	TelephonyInfo telephonyInfo;
	
	public static Uri SIMURI ;

	public static  ProgressDialog progressDialog;
	public static int phoneContactNumber;
	public static int simContactNumber;
	Fragment mFragment;
	private int CREDIT = 0;
	public static List<CTContactModel> contactModelList;
	public static List<CTContactModel> contactModelSimList;
	public static Map<String,CTContactModel> contactModelMap;
	public static boolean allContactSelect=true;
	public static  CTContactAdapter mAdapter;
	public static CTContactAdapter mAdapterSim;
	private static Context mContaxt;
	public static int numberLength = 8;
	public static int SELECTION_TAB ;
	public static TextView phoneHeaderView;
	private static TextView simHeaderView;
	static List<CTContactModel> tempAdapterList;
	static List<CTContactModel> tempSimAdapterList;
	//TextView actionBarHeader;

	private int counter = 0;
	//private static View rootView;
	static final String SELECTION = "((" + ContactsContract.Data.DISPLAY_NAME+ " NOTNULL) AND (" + ContactsContract.Data.DISPLAY_NAME+ " != '' ) AND (" +ContactsContract.CommonDataKinds.Phone.HAS_PHONE_NUMBER+ " > 0))";
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_ctcontacts);
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
		mContaxt = this;
		// Inflate the layout for this fragment
		//rootView = this.getLayoutInflater().inflate(R.layout.fragment_ctcontacts, null, false);
		// Set up the action bar.
		final ActionBar actionBar = getSupportActionBar();
		actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
		//		actionBar.setDisplayShowTitleEnabled(true);		            
		//actionBar.setCustomView(R.layout.custom_action); //load your layout
		//actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_HOME|ActionBar.DISPLAY_SHOW_CUSTOM); //show it 
		actionBar.setDisplayHomeAsUpEnabled(true);

		//actionBarHeader = (TextView) actionBar.getCustomView().findViewById(R.id.tn_contact_actionbar_header);

		String strCredit = CTUtils.getPreference(CTUtils.ARG_CREDIT, this);
		try{
			CREDIT = Integer.parseInt(strCredit);

		}catch (Exception e) {
			CREDIT = 20;
			CTUtils.savePreference(CTUtils.ARG_CREDIT, CREDIT+"", this);
		}




		telephonyInfo = TelephonyInfo.getInstance(this);


		SELECTION_TAB = 0;
		//init progress bar 
		progressDialog = new ProgressDialog(CTContactsActivity.this); 
		progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);  	
		progressDialog.setTitle("Please wait ...");
		//    progressDialog.setMessage("Loading application View, please wait...");  
		//This dialog can't be canceled by pressing the back key  
		progressDialog.setCancelable(false);  
		//This dialog isn't indeterminate  
		progressDialog.setIndeterminate(false);  
		//The maximum number of items is 100  
		progressDialog.setMax(100);  
		//Set the current progress to zero  
		progressDialog.setProgress(0);  


		// Create the adapter that will return a fragment for each of the three
		// primary sections of the activity.
		mSectionsPagerAdapter = new SectionsPagerAdapter(
				getSupportFragmentManager());

		// Set up the ViewPager with the sections adapter.
		mViewPager = (ViewPager) findViewById(R.id.pager);
		mViewPager.setAdapter(mSectionsPagerAdapter);

		// When swiping between different sections, select the corresponding
		// tab. We can also use ActionBar.Tab#select() to do this if we have
		// a reference to the Tab.
		mViewPager
		.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
			@Override
			public void onPageSelected(int position) {
				SELECTION_TAB = position;
				actionBar.setSelectedNavigationItem(position);
			}
		});

		// For each of the sections in the app, add a tab to the action bar.
		for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
			// Create a tab with text corresponding to the page title defined by
			// the adapter. Also specify this Activity object, which implements
			// the TabListener interface, as the callback (listener) for when
			// this tab is selected.
			actionBar.addTab(actionBar.newTab()
					.setText(mSectionsPagerAdapter.getPageTitle(i))
					.setTabListener(this));
		}


		//init map of contact 
		contactModelMap = new HashMap<String, CTContactModel>();
		contactModelList = new ArrayList<CTContactModel>();
		contactModelSimList= new ArrayList<CTContactModel>();
		mAdapter = new CTContactAdapter(CTContactsActivity.this, R.layout.contact_row, contactModelList);
		mAdapterSim = new CTContactAdapter(CTContactsActivity.this, R.layout.contact_row, contactModelSimList);
	}



	private void onActionBarHeaderClick() {
		startPayActivity(false);

	}
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.ctcontacts, menu);
		return true;
	}


	@Override
	protected void onActivityResult(int req, int rep, Intent data) {
		super.onActivityResult(rep, req, data);
		String strCredit = CTUtils.getPreference(CTUtils.ARG_CREDIT, this);
		try{
			CREDIT = Integer.parseInt(strCredit);
			//actionBarHeader.setText(getString(R.string.ct_contacts_actionbar_layout, CREDIT));
		}catch (Exception e) {
		}

	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_convert) {


			final Dialog dialog = new Dialog(this);
			dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
			dialog.getWindow().setBackgroundDrawableResource(R.drawable.ctcontacts_dialog_background);

			//LinearLayout ll = (LinearLayout) getLayoutInflater().inflate(R.layout.fragment_dialog_ctcontacts, null);			
			dialog.getWindow().setContentView(R.layout.fragment_dialog_ctcontacts);
			TextView txtv1 = (TextView) dialog.findViewById(R.id.ct_contacts_dialog_nbre_mot_a_convertir);
			txtv1.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					startPayActivity(true);
					dialog.dismiss();
				}
			});

			TextView txtv2 = (TextView) dialog.findViewById(R.id.ct_contacts_dialog_nbre_mot_a_retablir);

			txtv2.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {

					new AlertDialog.Builder(CTContactsActivity.this)
					.setTitle(R.string.ct_paiement_confirm_header)
					.setMessage(getString(R.string.ct_paiement_confirm_rollback))
					.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {

							//							if(CTUtils.autoSynchroniseService != null){
							//								CTUtils.autoSynchroniseService.cancel(true);
							//								CTUtils.autoSynchroniseService = null;
							//							}
							new  UndoConversionContacts().execute();

						}
					})
					.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {									
						}})
						.setIcon(android.R.drawable.ic_dialog_info)
						.show();
					dialog.dismiss();

				}
			});
			if(SELECTION_TAB == 0){
				txtv1.setText(String.format(getString(R.string.ct_contacts_dialog_nbre_mot_a_convertir), CTUtils.getContactCount(this, contactModelList)));
				txtv2.setText(String.format(getString(R.string.ct_contacts_dialog_nbre_mot_a_retablir), CTUtils.getConvertContactCount(this, contactModelList)));
			}else{

				txtv1.setText(String.format(getString(R.string.ct_contacts_dialog_nbre_mot_a_convertir), CTUtils.getContactCount(this, contactModelSimList)));
				txtv2.setText(String.format(getString(R.string.ct_contacts_dialog_nbre_mot_a_retablir), CTUtils.getConvertContactCount(this, contactModelSimList)));

			}
			dialog.show();


			return true;
		}
		if (id == R.id.action_select) {

			allContactSelect = !allContactSelect;
			for (CTContactModel ctContactModel : contactModelMap.values()) {
				ctContactModel.setSelected(allContactSelect);
			}
			/*for (CTContactModel ctContactModel : contactModelList) {
				ctContactModel.setSelected(allContactSelect);
			}*/
			mAdapter.notifyDataSetChanged();
			mAdapterSim.notifyDataSetChanged();
			return true;
		}
		if( id  == R.id.action_synchronise){

			Intent intent = new Intent(this, CTSynchroniserActivity.class);
			startActivity(intent);
			overridePendingTransition(R.anim.activity_in, R.anim.activity_out);
		}


		if(id ==android.R.id.home){

			// This ID represents the Home or Up button. In the case of this
			// activity, the Up button is shown. Use NavUtils to allow users
			// to navigate up one level in the application structure. For
			// more details, see the Navigation pattern on Android Design:
			//
			// http://developer.android.com/design/patterns/navigation.html#up-vs-back
			//

			Intent upIntent = NavUtils.getParentActivityIntent(this);
			upIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP); 
			NavUtils.navigateUpTo(this, upIntent);
		}
		return super.onOptionsItemSelected(item);
	}
	private void startPayActivity(boolean SHOW_MENU_VIEW){
		Intent intent = new Intent(CTContactsActivity.this, CTPaiementActivity.class);	
		if(SELECTION_TAB == 0)
			intent.putExtra(CTUtils.ARG_PHONE_CONTACT_COUNT,  CTUtils.getContactCount(this,contactModelList));
		else
			intent.putExtra(CTUtils.ARG_SIM_CONTACT_COUNT,  CTUtils.getContactCount(this,contactModelSimList));

		intent.putExtra("SHOW_MENU_VIEW", SHOW_MENU_VIEW );
		intent.putExtra(CTUtils.ARG_SELECTION_TAB, SELECTION_TAB );


		startActivityForResult(intent, 1002);
	}
	@Override
	public void onTabSelected(ActionBar.Tab tab,
			FragmentTransaction fragmentTransaction) {
		// When the given tab is selected, switch to the corresponding page in
		// the ViewPager.
		mViewPager.setCurrentItem(tab.getPosition());
	}

	@Override
	public void onTabUnselected(ActionBar.Tab tab,
			FragmentTransaction fragmentTransaction) {

		PlaceholderFragment.cancelTask();
	}

	@Override
	public void onTabReselected(ActionBar.Tab tab,
			FragmentTransaction fragmentTransaction) {
	}

	/**
	 * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
	 * one of the sections/tabs/pages.
	 */
	public class SectionsPagerAdapter extends FragmentPagerAdapter {

		public SectionsPagerAdapter(FragmentManager fm) {
			super(fm);
		}

		@Override
		public Fragment getItem(int position) {
			// getItem is called to instantiate the fragment for the given page.
			// Return a PlaceholderFragment (defined as a static inner class
			// below).

			mFragment = PlaceholderFragment.newInstance(position + 1);
			switch (position) {
			case 0:
				mFragment = PlaceholderFragment.newInstance(position + 1);
				return mFragment;
			case 1:
				mFragment =  SimFragment.newInstance(position + 1);
				return mFragment;

			}
			return mFragment;
		}

		@Override
		public int getCount() {
			//if(!telephonyInfo.isSIM2Ready())
			return 2;
			//return 3;
		}

		@Override
		public CharSequence getPageTitle(int position) {
			Locale l = Locale.getDefault();
			switch (position) {
			case 0:
				return getString(R.string.title_section1).toUpperCase(l);
			case 1:
				return getString(R.string.title_section4).toUpperCase(l);
			case 2:
				return getString(R.string.title_section5).toUpperCase(l);
			}
			return null;
		}
	}

	/**
	 * A placeholder fragment containing a simple view.
	 */
	public static class PlaceholderFragment extends Fragment {
		/**
		 * The fragment argument representing the section number for this
		 * fragment.
		 */
		private static final String ARG_SECTION_NUMBER = "section_number";

		private static View rootView;

		public   ListView lstContacts;
		private   LoadContact mTask;
		private  int sectionNumber = 0;



		/**
		 * Returns a new instance of this fragment for the given section number.
		 */
		public static PlaceholderFragment newInstance(int sectionNumber) {
			PlaceholderFragment fragment = new PlaceholderFragment();
			fragment.sectionNumber = sectionNumber;
			Bundle args = new Bundle();
			args.putInt(ARG_SECTION_NUMBER, sectionNumber);
			fragment.setArguments(args);
			System.out.println(ARG_SECTION_NUMBER+" = "+sectionNumber);
			return fragment;
		}

		public static void cancelTask(){
			//			if(mTask!=null){
			//				mTask.cancel(true);
			//				lstContacts.removeAllViews();
			//			}
			//	ischange = true;
		}

		public PlaceholderFragment() {
		}


		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup container,
				Bundle savedInstanceState) {
			rootView = inflater.inflate(R.layout.fragment_ctcontacts,
					container, false);
			lstContacts = (ListView) rootView.findViewById(R.id.list_contacts);

			lstContacts.setOnItemClickListener(new OnItemClickListener(){

				public void onItemClick(AdapterView<?> parent, View view, int position, long arg3) 
				{

					CTContactModel contactModel = (CTContactModel) mAdapter.getItem(position);					
					contactModel.setSelected(!contactModel.isSelected());
					mAdapter.notifyDataSetChanged();
				}
			});



			lstContacts.setAdapter(mAdapter);
			phoneHeaderView = (TextView) rootView.findViewById(R.id.section_label);

			Cursor contactsCursor = getActivity().getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, SELECTION, null,null);
			String str = String.format(getString(R.string.ct_contactlist_header),0);
			phoneContactNumber = contactsCursor.getCount();
			phoneHeaderView.setText(str);


			//get Sim information

			Uri simUri = Uri.parse("content://icc/adn"); 
			Cursor cursorSim = getActivity().getContentResolver().query(simUri,null,null,null,null);
			if(cursorSim != null)
			simContactNumber = cursorSim.getCount();

			mTask = new LoadContact();
			mTask.execute(this);
			return rootView;
		}

		@Override
		public void onDestroyView() {

			if(!mTask.isCancelled())
			{
				mTask.cancel(true);
			}
			if (rootView != null) {
				ViewGroup parentViewGroup = (ViewGroup) rootView.getParent();
				if (parentViewGroup != null) {
					parentViewGroup.removeAllViews();
				}
			}
			super.onDestroyView();
		}

		public  class LoadContact extends AsyncTask<PlaceholderFragment, Void, Cursor>{


			@Override
			protected Cursor doInBackground(PlaceholderFragment... args) {
				Cursor result = null;
				result = loadOnPhone();
				return result;
			}

			private Cursor loadOnPhone(){

				Uri contactsUri = ContactsContract.Contacts.CONTENT_URI;
				Context curentContext = getActivity();
				// Querying the table ContactsContract.Contacts to retrieve all the contacts
				Cursor contactsCursor = curentContext.getContentResolver().query(contactsUri, null, SELECTION, null, 
						"UPPER("+ContactsContract.Contacts.DISPLAY_NAME + ") ASC ");

				int counter = 0;
				int counterNumber = 0;
				tempAdapterList = new ArrayList<CTContactModel>();
				try{

					if (contactsCursor.getCount() > 0) {
						while (contactsCursor.moveToNext()) {
							counter++;
							long contactId = contactsCursor.getLong(contactsCursor.getColumnIndex("_ID"));
							Uri dataUri = ContactsContract.Data.CONTENT_URI;
							// Querying the table ContactsContract.Data to retrieve individual items like
							// home phone, mobile phone, work email etc corresponding to each contact 
							Cursor dataCursor = curentContext.getContentResolver().query(dataUri, null, 
									ContactsContract.Data.CONTACT_ID + "=" + contactId, 
									null, null);
							dataCursor.moveToFirst();

							String displayName = dataCursor.getString(dataCursor.getColumnIndex(ContactsContract.Data.DISPLAY_NAME ));


							byte[] photoByte=null;


							ArrayList<CTNumberModel> numbers = new ArrayList<CTNumberModel>();
							if (Integer .parseInt(contactsCursor.getString(contactsCursor .getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {

								Cursor pCur = curentContext.
										getContentResolver().
										query( ContactsContract.CommonDataKinds.Phone.CONTENT_URI, 
												null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[] { contactId+"" }, null); 

								while (pCur.moveToNext()) { 
									String phone  = pCur .getString(pCur .getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
									int phoneType  = pCur .getInt(pCur .getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE));

									CTNumberModel ctNum = new CTNumberModel(phone, phoneType);
									if(!numbers.contains(ctNum) && phone.length()>=numberLength)
									{
										numbers.add(ctNum);
									}

								}
								pCur.close(); 				
							}
							Bitmap 	bitmap = BitmapFactory.
									decodeResource(curentContext
											.getResources(),
											R.drawable.user_avatar);

							if(dataCursor.getString(dataCursor.getColumnIndex("mimetype")).equals(ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE)){								
								photoByte = dataCursor.getBlob(dataCursor.getColumnIndex("data15"));

								if(photoByte != null) {							
									bitmap = BitmapFactory.decodeByteArray(photoByte, 0, photoByte.length);
									System.out.println("bitmap.getWidth()"+bitmap.getWidth());
									// Getting Caching directory 
									File cacheDirectory = curentContext.getCacheDir();

									// Temporary file to store the contact image 
									File tmpFile = new File(cacheDirectory.getPath() + "/wpta_"+contactId+".png");

									// The FileOutputStream to the temporary file
									try {
										FileOutputStream fOutStream = new FileOutputStream(tmpFile);

										// Writing the bitmap to the temporary file as png file
										bitmap.compress(Bitmap.CompressFormat.PNG,100, fOutStream);

										// Flush the FileOutputStream
										fOutStream.flush();

										//Close the FileOutputStream
										fOutStream.close();

									} catch (Exception e) {
										e.printStackTrace();
									}


								}


							}

							boolean change = false;
							if(numbers.size()!=0){
								final CTContactModel contactMode = new  CTContactModel(contactId, displayName, bitmap,numbers,  true, Integer.valueOf(getString(R.string.notto_converted_int)));
								CTUtils.getProvider(getActivity(),contactMode);;
								for (CTNumberModel ctNumberModel : contactMode.getNumbers()) {
									if(ctNumberModel.isCameroonian())
									{
										counterNumber++;
										if((counterNumber%2)==0){
											change = true;
										}
									}
								}

								final int tempCounter  = counterNumber;
								final boolean tempChange = change;
								((Activity)curentContext).runOnUiThread(new Runnable() {
									public void run() {

										tempAdapterList.add(contactMode);
										String _id = String.valueOf(contactMode.getId());
										CTContactModel ctContacM = contactModelMap.get(_id);
										if(ctContacM==null)
										{
											contactModelMap.put(_id, contactMode);
											String str = String.format(getString(R.string.ct_contactlist_header),tempCounter);
											phoneHeaderView.setText(str);
										}
										if(tempChange)
										{

											mAdapter.getmListOffContact().addAll(tempAdapterList);
											mAdapter.notifyDataSetChanged();
											tempAdapterList = new ArrayList<CTContactModel>();
										}
									}
								});
							}
							dataCursor.close();

							progressDialog.setProgress(counter*100/(phoneContactNumber+simContactNumber)); 
						}
						((Activity)curentContext).runOnUiThread(new Runnable() {
							public void run() {		
								if(tempAdapterList!=null && tempAdapterList.size()>0)
								{

									mAdapter.getmListOffContact().addAll(tempAdapterList);
									mAdapter.notifyDataSetChanged();
									tempAdapterList = new ArrayList<CTContactModel>();
								}
							}
						});


					}
				}catch (Exception e) {
					Log.e(CTContactsActivity.class.getName(), e.getMessage()+"");
					e.printStackTrace();
				}
				return contactsCursor;

			}		

			@Override
			public void onPreExecute() {	
				//	lockScreenOrientation();
				progressDialog.show();  
			}

			@Override
			public void onPostExecute(Cursor result) {	

				progressDialog.dismiss();

				//mAdapter.getmListOffContact().addAll(listOffContact);
				if(result!=null)
					result.close();
				//unLockScreenOrientation();


			}



			private void lockScreenOrientation()
			{

				int currentOrientation = getResources().getConfiguration().orientation;
				if(currentOrientation==Configuration.ORIENTATION_PORTRAIT)
				{
					getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
				}
				else{
					getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
				}
			}


			private void unLockScreenOrientation()
			{

				getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);

			}


		}

	}

	public static class SimFragment extends Fragment {
		/**
		 * The fragment argument representing the section number for this
		 * fragment.
		 */
		private static final String ARG_SECTION_NUMBER = "section_number";
		private View rootView;

		public   ListView lstContacts;
		private   LoadContact mTask;		


		/**
		 * Returns a new instance of this fragment for the given section number.
		 */
		public static SimFragment newInstance(int sectionNumber) {
			SimFragment fragment = new SimFragment();

			Bundle args = new Bundle();
			args.putInt(ARG_SECTION_NUMBER, sectionNumber);
			fragment.setArguments(args);

			return fragment;
		}

		public static void cancelTask(){
			//			if(mTask!=null){
			//				mTask.cancel(true);
			//				lstContacts.removeAllViews();
			//			}
			//	ischange = true;
		}

		public SimFragment() {
		}

		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup container,
				Bundle savedInstanceState) {

			rootView = inflater.inflate(R.layout.fragment_ctsim1_contact,
					container, false);
			lstContacts = (ListView) rootView.findViewById(R.id.list_contacts_sim1);
			lstContacts.setOnItemClickListener(new OnItemClickListener(){

				public void onItemClick(AdapterView<?> parent, View view, int position, long arg3) 
				{
					CTContactModel contactModel = (CTContactModel) mAdapterSim.getItem(position);
					contactModel.setSelected(!contactModel.isSelected());   
					mAdapterSim.notifyDataSetChanged();
				}
			});
			lstContacts.setAdapter(mAdapterSim);
			simHeaderView = (TextView) rootView.findViewById(R.id.ct_contactlist_header_sim1);
			//Uri simUri = Uri.parse("content://icc/adn"); 
			//Cursor cursorSim = getActivity().getContentResolver().query(simUri,null,null,null,null);
			String str = String.format(getString(R.string.ct_contactlist_header),0);				
			simHeaderView.setText(str);

			mTask = new LoadContact();
			mTask.execute(this);
			return rootView;
		}

		@Override
		public void onDestroyView() {


			if(!mTask.isCancelled())
			{
				mTask.cancel(true);
			}
			if (rootView != null) {
				ViewGroup parentViewGroup = (ViewGroup) rootView.getParent();
				if (parentViewGroup != null) {
					parentViewGroup.removeAllViews();
				}
			}
			super.onDestroyView();
		}

		public  class LoadContact extends AsyncTask<SimFragment, Void, Cursor>{

			@Override
			protected Cursor doInBackground(SimFragment... args) {
				Cursor result = null;				
				result = loadOnSim1();				
				return result;
			}


			private Cursor loadOnSim1(){

				//				String DYSPLAYNAME = android.provider.Contacts.PeopleColumns.NAME;
				//				String NUMBER = android.provider.Contacts.PhonesColumns.NUMBER;
				//                String _ID = android.provider.BaseColumns._ID ;
				Uri simUri15 = Uri.parse("content://sim/adn/");
				Uri simUri16 = Uri.parse("content://icc/adn"); 
				try{

					Cursor cursorSim = getActivity().getContentResolver().query(simUri16,null,null,null,"UPPER(name) COLLATE LOCALIZED ASC ");
					SIMURI = simUri16;
					if(cursorSim != null && cursorSim.getCount() == 0){
						cursorSim  = getActivity().getContentResolver().query(simUri15,null,null,null,"UPPER(name) COLLATE LOCALIZED ASC ");
						SIMURI = simUri15;
					}
					String simPhonename = null; 
					String simphoneNo = null;
					String id = null;
					Bitmap 	bitmap = BitmapFactory.decodeResource(getActivity().getResources(), R.drawable.user_avatar);
					int counter = 0;
					int numberCounter = 0;
					tempSimAdapterList = new ArrayList<CTContactModel>();
					if(cursorSim.getCount()>0){
						while (cursorSim.moveToNext()) 
						{      
							counter++;
							ArrayList<CTNumberModel> numbers = new ArrayList<CTNumberModel>();
							simPhonename =cursorSim.getString(cursorSim.getColumnIndex("name"));
							simphoneNo = cursorSim.getString(cursorSim.getColumnIndex("number"));
							id = cursorSim.getString(cursorSim.getColumnIndex("_id"));
							//		                simphoneNo.replaceAll("\\D","");
							//		                simphoneNo.replaceAll("&", "");
							//		                simPhonename=simPhonename.replace("|","");

							if(simphoneNo == null)
								continue;
							CTNumberModel ctNum = new CTNumberModel(simphoneNo);
							if(!numbers.contains(ctNum)  && simphoneNo.length() >= numberLength)
							{
								numbers.add(new CTNumberModel(simphoneNo));

							}

							boolean change = false;
							if(numbers.size()!=0){
								final CTContactModel contactMode = new  CTContactModel(Long.parseLong(id),simPhonename,bitmap, numbers,true,Integer.valueOf(getString(R.string.notto_converted_int)));
								CTUtils.getProvider(getActivity(),contactMode);
								for (CTNumberModel ctNumberModel : contactMode.getNumbers()) {
									if(ctNumberModel.isCameroonian())
									{

										numberCounter++;
										if((numberCounter%2)==0){
											change = true;
										}
									}

								}
								final int tempCounter = numberCounter;
								final boolean tempChange = change;
								getActivity().runOnUiThread(new Runnable() {
									public void run() {

										tempSimAdapterList.add(contactMode);
										String _id = String.valueOf(contactMode.getId());
										CTContactModel ctContacM = contactModelMap.get(_id);

										if(ctContacM==null)
										{
											contactModelMap.put(_id, contactMode);

											String str = String.format(getString(R.string.ct_contactlist_header),tempCounter);				
											simHeaderView.setText(str);

										}
										if(tempChange)
										{

											mAdapterSim.getmListOffContact().addAll(tempSimAdapterList);
											mAdapterSim.notifyDataSetChanged();
											tempSimAdapterList = new ArrayList<CTContactModel>();
										}

									}
								});

							}


							progressDialog.setProgress(counter*100/(phoneContactNumber+simContactNumber)); 

						} 
						getActivity().runOnUiThread(new Runnable() {
							public void run() {		
								if(tempSimAdapterList!=null && tempSimAdapterList.size()>0)
								{

									mAdapterSim.getmListOffContact().addAll(tempSimAdapterList);
									mAdapterSim.notifyDataSetChanged();
									tempSimAdapterList = new ArrayList<CTContactModel>();
								}
							}
						});
					}

					return cursorSim;
				}catch (Exception e) {
					Log.e(CTSIMDao.class.getName(), e.getMessage()+"");
				}
				return null;
			}


			@Override
			public void onPreExecute() {	
				progressDialog.show();
			}

			@Override
			public void onPostExecute(Cursor result) {	
				progressDialog.dismiss();
				//mAdapter.getmListOffContact().addAll(listOffContact);
				if(result!=null)
					result.close();
				//unLockScreenOrientation();


			}

		}

	}



	public static class TelephonyInfo {

		private static TelephonyInfo telephonyInfo;
		private String imeiSIM1;
		private String imeiSIM2;
		private boolean isSIM1Ready;
		private boolean isSIM2Ready;

		public String getImeiSIM1() {
			return imeiSIM1;
		}

		/*public static void setImeiSIM1(String imeiSIM1) {
	        TelephonyInfo.imeiSIM1 = imeiSIM1;
	    }*/

		public String getImeiSIM2() {
			return imeiSIM2;
		}

		/*public static void setImeiSIM2(String imeiSIM2) {
	        TelephonyInfo.imeiSIM2 = imeiSIM2;
	    }*/

		public boolean isSIM1Ready() {
			return isSIM1Ready;
		}

		/*public static void setSIM1Ready(boolean isSIM1Ready) {
	        TelephonyInfo.isSIM1Ready = isSIM1Ready;
	    }*/

		public boolean isSIM2Ready() {
			return isSIM2Ready;
		}

		/*public static void setSIM2Ready(boolean isSIM2Ready) {
	        TelephonyInfo.isSIM2Ready = isSIM2Ready;
	    }*/

		public boolean isDualSIM() {
			return imeiSIM2 != null;
		}

		private TelephonyInfo() {
		}

		public static TelephonyInfo getInstance(Context context){

			if(telephonyInfo == null) {

				telephonyInfo = new TelephonyInfo();

				TelephonyManager telephonyManager = ((TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE));

				telephonyInfo.imeiSIM1 = telephonyManager.getDeviceId();
				telephonyInfo.imeiSIM2 = null;

				try {
					//	                telephonyInfo.imeiSIM1 = getDeviceIdBySlot(context, "getDeviceIdGemini", 0);
					//	                telephonyInfo.imeiSIM2 = getDeviceIdBySlot(context, "getDeviceIdGemini", 1);
					telephonyInfo.imeiSIM1 = getDeviceIdBySlot(context, "getDeviceIdDs", 0);
					telephonyInfo.imeiSIM2 = getDeviceIdBySlot(context, "getDeviceIdDs", 1);
				} catch (GeminiMethodNotFoundException e) {
					e.printStackTrace();

					try {
						telephonyInfo.imeiSIM1 = getDeviceIdBySlot(context, "getDeviceId", 0);
						telephonyInfo.imeiSIM2 = getDeviceIdBySlot(context, "getDeviceId", 1);
					} catch (GeminiMethodNotFoundException e1) {
						//Call here for next manufacturer's predicted method name if you wish
					//	e1.printStackTrace();
					}
				}

				telephonyInfo.isSIM1Ready = telephonyManager.getSimState() == TelephonyManager.SIM_STATE_READY;
				telephonyInfo.isSIM2Ready = false;

				try {
					telephonyInfo.isSIM1Ready = getSIMStateBySlot(context, "getSimStateGemini", 0);
					telephonyInfo.isSIM2Ready = getSIMStateBySlot(context, "getSimStateGemini", 1);
				} catch (GeminiMethodNotFoundException e) {

				//	e.printStackTrace();

					try {
						telephonyInfo.isSIM1Ready = getSIMStateBySlot(context, "getSimState", 0);
						telephonyInfo.isSIM2Ready = getSIMStateBySlot(context, "getSimState", 1);
					} catch (GeminiMethodNotFoundException e1) {
						//Call here for next manufacturer's predicted method name if you wish
						//e1.printStackTrace();
					}
				}
			}

			return telephonyInfo;
		}

		private static String getDeviceIdBySlot(Context context, String predictedMethodName, int slotID) throws GeminiMethodNotFoundException {

			String imei = null;

			TelephonyManager telephony = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);

			try{

				Class<?> telephonyClass = Class.forName(telephony.getClass().getName());

				Class<?>[] parameter = new Class[1];
				parameter[0] = int.class;
				Method getSimID = telephonyClass.getMethod(predictedMethodName, parameter);

				Object[] obParameter = new Object[1];
				obParameter[0] = slotID;
				Object ob_phone = getSimID.invoke(telephony, obParameter);

				if(ob_phone != null){
					imei = ob_phone.toString();

				}
			} catch (Exception e) {
				//e.printStackTrace();
				throw new GeminiMethodNotFoundException(predictedMethodName);
			}

			return imei;
		}

		private static  boolean getSIMStateBySlot(Context context, String predictedMethodName, int slotID) throws GeminiMethodNotFoundException {

			boolean isReady = false;

			TelephonyManager telephony = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);

			try{

				Class<?> telephonyClass = Class.forName(telephony.getClass().getName());

				Class<?>[] parameter = new Class[1];
				parameter[0] = int.class;
				Method getSimStateGemini = telephonyClass.getMethod(predictedMethodName, parameter);

				Object[] obParameter = new Object[1];
				obParameter[0] = slotID;
				Object ob_phone = getSimStateGemini.invoke(telephony, obParameter);

				if(ob_phone != null){
					int simState = Integer.parseInt(ob_phone.toString());
					if(simState == TelephonyManager.SIM_STATE_READY){
						isReady = true;
					}
				}
			} catch (Exception e) {

				throw new GeminiMethodNotFoundException(predictedMethodName);
			}

			return isReady;
		}


		private static class GeminiMethodNotFoundException extends Exception {

			private static final long serialVersionUID = -996812356902545308L;

			public GeminiMethodNotFoundException(String info) {
				super(info);
			}
		}
	}

	private class UndoConversionContacts extends AsyncTask<Void, Void, Void>{

		@Override
		protected void onPreExecute() {
			showProgress(true);
			super.onPreExecute();
		}
		@Override
		protected Void doInBackground(Void... params) {


			if(SELECTION_TAB == 0 )
				updateAll(SELECTION_TAB, contactModelList	);
			else 
				updateAll(SELECTION_TAB, contactModelSimList	);
			return null;
		}
		private void updateAll(int selectedTab, List<CTContactModel> listOfContact){

			for (CTContactModel ctContactModel : listOfContact) {

				if (ctContactModel.isSelected() && (ctContactModel.getConvertCode()==Integer.valueOf(getString(R.string.is_converted_int)).intValue()||ctContactModel.getConvertCode()==Integer.valueOf(getString(R.string.notall_converted_int)).intValue())){
					updateContact(ctContactModel, selectedTab);
				}
			}


		}
		@Override
		protected void onPostExecute(Void result) {
			showProgress(false);

			CTContactsActivity.this.runOnUiThread(new Runnable() {
				public void run() {
					if(CTContactsActivity.SELECTION_TAB == 0){

						CTContactsActivity.mAdapter.notifyDataSetChanged();
					}else
						CTContactsActivity.mAdapterSim.notifyDataSetChanged();
				}});

			String toast = String.format(CTContactsActivity.this.getString(R.string.notification_numero_rollback), counter);
			Toast.makeText(CTContactsActivity.this, toast, Toast.LENGTH_LONG).show();
			super.onPostExecute(result);
		}

		private void showProgress(final boolean show) {


			if(show)
				progressDialog = ProgressDialog.show(CTContactsActivity.this, "", "Loading...");
			else
				progressDialog.dismiss();
		}


		private void updateContact(CTContactModel contact, int selectedTab){
			Uri contactsUri = ContactsContract.Contacts.CONTENT_URI;		
			if(selectedTab == 1){

				CTNumberModel ctNumberModel = contact.getNumbers().get(0);
				if(ctNumberModel.isCameroonian() && !ctNumberModel.isConvertable()){
					contactsUri = SIMURI; 
					ContentValues values = new ContentValues();
					values.put("tag", contact.getName());  
					values.put("newTag", contact.getName());  
					values.put("number", ctNumberModel.getNumber());  		  
					values.put("newNumber", ctNumberModel.getRollBackNumber());
					getContentResolver().update(contactsUri, values, null, null);
					ctNumberModel.setNumber(ctNumberModel.getRollBackNumber());
					counter++;
				}
			}else{

				ArrayList<CTNumberModel> listOfNumber = contact.getNumbers();
				for (CTNumberModel ctNumberModel : listOfNumber) {

					if(ctNumberModel.isCameroonian() && ! ctNumberModel.isConvertable()){

						String where = ContactsContract.Data.CONTACT_ID + " = ? AND " + 
								ContactsContract.Data.MIMETYPE + " = ? AND " +
								String.valueOf(ContactsContract.CommonDataKinds.Phone.TYPE) + " = ? ";

						String[] params = new String[] {contact.getId()+"",
								ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE,
								String.valueOf(ctNumberModel.getNumberType())};				

						ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();

						ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
								.withSelection(where, params)
								.withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, ctNumberModel.getRollBackNumber())
								.build());
						try {
							CTContactsActivity.this.getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
							ctNumberModel.setNumber(ctNumberModel.getRollBackNumber());
							counter++;
						} catch (RemoteException e) {
							e.printStackTrace();
						} catch (OperationApplicationException e) {					
							e.printStackTrace();
						}
					}

				}
			}

			CTUtils.getProvider(CTContactsActivity.this, contact);

		}




	}

	@Override
	public void onBackPressed() {
		// finish() is called in super: we only override this method to be able to override the transition
		super.onBackPressed();

		overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);
	}

}
